package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.responseClasses.NotificationObject;
import com.storyroad.utils.CreateNotification;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class Notifications
 */
public class Notifications extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Notifications() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Gets the notifications for a registered user. A list of {@link com.storyroad.responseClasses.NotificationObject}
	 * instances which contain the notification data is returned to the front-end. Please refer to
	 * {@link com.storyroad.utils.CreateNotification} for a detailed explanation on how the notification system works. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int u_id;
		int source_u_id;
		byte n_type;
		int target_s_id;
		String parentStoryTitle;
		String username;
		String sourceUsername;
		String storyTitle;
		ArrayList<NotificationObject> notifications = new ArrayList<NotificationObject>();
		ResultSet rs;
		PreparedStatement stmt = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		if (conn == null) {
			out.println("Correction error");
		} else {
			if (f_requestType.equals("Web")) {
				username = (String) request.getSession().getAttribute("username");
			} else {
				username = request.getParameter("username");
			}
			u_id = Utilities.getUserId(conn, username);
			try {
				// Get the notifications of this user
				stmt = conn.prepareStatement("SELECT source_u_id,n_type,target_s_id FROM " + TableNames.NOTIFICATION_TABLE
								+ " WHERE target_u_id LIKE ? ORDER BY date DESC");
				stmt.setString(1, "%," + u_id + ",%");
				rs = stmt.executeQuery();
				while (rs.next()) {
					source_u_id = rs.getInt("source_u_id");
					n_type = rs.getByte("n_type");
					target_s_id = rs.getInt("target_s_id");
					sourceUsername = Utilities.getUsername(conn, source_u_id);
					storyTitle = Utilities.getStoryTitle(conn, target_s_id);
					parentStoryTitle = Utilities.getParentStoryTitle(conn, target_s_id);
					// Verbalize the data in the Notification table to display it on the main page of a user.
					if (source_u_id != Utilities.getUserId(conn, username)) {
						notifications.add(CreateNotification.createNotificationObject(sourceUsername, n_type, storyTitle, target_s_id, source_u_id, parentStoryTitle));
					}
				}

				if (f_requestType.equals("Android")) {
					JSONObject notificationsJsonObject = new JSONObject();
					try {
						notificationsJsonObject.put("notifications", notifications);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(notificationsJsonObject.toString());
				} else if (f_requestType.equals("Web")) {
					request.setAttribute("notifications", notifications);
					request.getRequestDispatcher("MainPage.jsp").forward(request, response);
				} else {
					// DO NOTHING!
				}
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
